<template>
  <div class="m-tree">
    <el-input
      v-if="searchInput"
      v-model.trim="filterText"
      suffix-icon="el-icon-search"
      placeholder="请输入"
      class="search-input"
    />
    <div class="m-tree-content">
      <el-tree
        ref="treeRef"
        :filter-node-method="filterNodePro"
        :auto-expand-parent="false"
        :expand-on-click-node="false"
        :highlight-current="true"
        :default-expanded-keys="defaultExpandedKeys"
        :data="data"
        :props="props"
        :show-checkbox="showCheckbox"
        node-key="id"
        @node-expand="nodeExpand"
        @node-collapse="nodeCollapse"
        @node-click="handleNodeClick"
      >
        <template v-slot="{node,data}">
          <div v-if="customLabel">
            <slot :slotScope="{node,data}" />
          </div>
          <span v-else>{{ node.label }}</span>
        </template>
      </el-tree>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
// tree封装
@Component({
  name: 'MTree'
})
export default class extends Vue {
  @Prop({ required: true, default: () => [] })
  private defaultExpandedKeys!: any; // 默认展开
  @Prop({ default: [] }) private data!: any[]; // data
  @Prop({ default: {} }) private props!: any; // 默认一些属性配置
  @Prop({ default: false }) private searchInput!: boolean; // 是否显示过滤框
  @Prop({ default: false }) private showCheckbox!: boolean; //  是否显示checkbox
  @Prop({ default: false }) private customLabel!: boolean; //

  private filterText: string = '';

  @Watch('filterText')
  private onFilterText(v: string) {
    (this.$refs.treeRef as any).filter(v)
  }

  mounted() {}
  // 获取选择的
  getCheckedKeys(flag: boolean) {
    (this.$refs.treeRef as any).getCheckedKeys(flag)
  }
  // 过滤node
  filterNodePro(value: string, data: any) {
    if (!value) return true
    return data.label && data.label.indexOf(value) !== -1
  }
  // 设置当前key选中
  setCurrentKey(data: any, flag: boolean) {
    // flag若为 true 则仅设置叶子节点的选中状态，默认值为 false
    this.$nextTick(() => {
      (this.$refs.treeRef as any).setCurrentKey(data, flag)
    })
  }
  // 节点展开
  nodeExpand(data: any[]) {
    this.$emit('node-expand', data)
  }
  // 节点折叠
  nodeCollapse(data: any[]) {
    this.$emit('node-collapse', data)
  }
  // 节点点击
  handleNodeClick(e: any) {
    this.$emit('node-click', e)
  }
  // 鼠标右键
  clickRightEvent(e: any) {
    this.$emit('node-contextmenu', e)
  }
}
</script>
<style lang="scss">
// .m-tree {
//   height: 100%;
//   .search-input {
//     margin-bottom: 10px;
//   }
//   .m-tree-content {
//     height: calc(100% - 4px);
//     overflow: auto;
//     .el-tree {
//       .el-tree-node__content {
//         .el-checkbox {
//           margin-right: 6px;
//         }
//       }
//     }
//   }
// }
</style>
